
In C# introduce new concept is indexer. This is very useful some situation. Indexers allow our object to be used just like an array, or we can index the object using [] brackets just like array. We can say indexers are special type of property’s which adds logic that how can array or list store the values. Syntax of the indexers resembles to properties. We can use all access modifiers with indexers and also have return types. We can say indexers are regular members of a class. Indexers are use this keyword. Given bellow the example code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObjectTest
{
class Student
{
private int[] myArr = new int[5];
public int this[int ind]
{
get { return myArr[ind]; }
set { myArr[ind] = value; }
}
}
class Program
{
static void Main(string[] args)
{
Student stdObj = new Student();
stdObj[0] = 5;
Console.WriteLine("Value is Assign : "+ stdObj[0]);
Console.ReadKey();
}
}
}
In this code we use an int array and this array is private so we can’t access from another class. So, we use indexer to get and set value from another class. This indexer is public so we can access another class. Indexer can be overload.